package models

import (
	"github.com/zw2582/ginlib"
	"strconv"
	"time"
)

//AccountBillMonth 月账单
type AccountBillMonth struct {
	Id int `xorm:"pk autoincr"`
	AccountId int
	Date int `xorm:"int(10) comment('年月数字')"`
	Amount float64 `xorm:"decimal(12,2) comment('金额*元')"`
	OrderNo string `xorm:"varchar(64) comment('结账单号')"`
	Status int `xorm:"tinyint(1) comment('1.已结 0.未结')"`
}

func init()  {
	ginlib.XormAddWaitSync(new(AccountBillMonth))
}

//AccountBillMonthAdd 增加月账单金额
func AccountBillMonthAdd(accountId int, money float64)  {
	date,_ := strconv.Atoi(time.Now().Format("200601"))
	bill := AccountBillMonth{}

	session := DB.NewSession()
	defer session.Close()

	if err := session.Begin(); err != nil {
		panic(err)
	}

	session.Where("date=? and account_id=?", date, accountId).ForUpdate().Get(&bill)
	if bill.Id == 0 {
		bill.Amount = money
		bill.Date = date
		bill.AccountId = accountId
		bill.Status = 0 //1.已结 0.未结
		if _, err := session.Insert(&bill); err != nil {
			panic(err)
		}
	} else {
		bill.Amount += money
		if _, err := session.ID(bill.Id).Update(&bill); err != nil {
			panic(err)
		}
	}
	if err := session.Commit(); err != nil {
		panic(err)
	}
}